package org.example.mq.dataCenter;


import org.example.mq.MqApplication;
import org.example.mq.mqserver.core.Binding;
import org.example.mq.mqserver.core.Exchange;
import org.example.mq.mqserver.core.MSGQueue;
import org.example.mq.mqserver.coreenum.ExchangeType;
import org.example.mq.mqserver.mapper.IMetaMapper;

import java.io.File;
import java.util.List;


//对数据库进行统一的管理
public class DataBaseMange {

    private IMetaMapper iMetaMapper;
    public void init(){
        iMetaMapper = MqApplication.context.getBean(IMetaMapper.class);
        File fileDir = new File("./data");
        fileDir.mkdirs();
        if(!checkDBExists()){
            createTable();
            createDefaultData();
            System.out.println("数据加载完成");
        }else {
            System.out.println("数据已存在");
        }
    }

    public void deleteDB(){
        File file = new File("./data/meta.db");
        if(file.exists()){
            file.delete();
            System.out.println("数据文件删除成功");
        }else {
            System.out.println("数据文件不存在");
        }

        File fileDir = new File("./data");
        if(fileDir.exists()){
            fileDir.delete();
            System.out.println("data文件删除成功");
        }else {
            System.out.println("data文件不存在");
        }

    }




    private boolean checkDBExists() {
        File file = new File("./data/meta.db");
        if(file.exists()){
            return true;
        }else {
            return false;
        }
    }

    private void createTable() {
        iMetaMapper.createExchangeTable();
        iMetaMapper.createMSGQueueTable();;
        iMetaMapper.createBindingTable();
        System.out.println("数据表创建完成");
    }

    private void createDefaultData() {
        Exchange exchange = new Exchange();
        exchange.setName("");
        exchange.setType(ExchangeType.DIRECT);
        exchange.setDurable(true);
        exchange.setAutoDelete(false);
        iMetaMapper.insertExchange(exchange);
        System.out.println("初始化已完成…");
    }

    public void insertExchange(Exchange exchange){
        iMetaMapper.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName){
        iMetaMapper.deleteExchange(exchangeName);
    }
    public List<Exchange> selectAllExchange(){
        return iMetaMapper.selectAllExchange();
    }

    public void insertMSGQueue(MSGQueue queue){
        iMetaMapper.insertMSGQueue(queue);
    }
    public void deleteMSGQueue(String queueName){
        iMetaMapper.deleteMSGQueue(queueName);
    }
    public List<MSGQueue> selectAllMSGQueue(){
        return iMetaMapper.selectAllMSGQueue();
    }

    public void insertBinding(Binding binding){
        iMetaMapper.insertBinding(binding);
    }
    public void deleteBinding(Binding binding){
        iMetaMapper.deleteBinding(binding);
    }

    public List<Binding> selectAllBinding(){
        return iMetaMapper.selectAllBinding();
    }
}
